import React, { Component } from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import { RaisedButton, TextField } from 'material-ui';
import './style.css';

class Mac extends Component {
    render() {
        const {error, userInfo, verifying, onSubmit, onChange} = this.props;
        return (
            <div>{
                verifying ?
                    <h2 style={{margin: '15%'}}>verifying</h2> :
                    <div>
                        <h2>Make a claim</h2>
                        { error && <p>error: {error}</p>}
                        <form onSubmit={ e => { e.preventDefault(); onSubmit(userInfo) }}>
                            <TextField floatingLabelText="first name" onChange={ e => onChange("firstName", e.target.value)} defaultValue={userInfo.firstName}></TextField><br/>
                            <TextField floatingLabelText="last name" onChange={ e => onChange("lastName", e.target.value)} defaultValue={userInfo.lastName}></TextField><br/>
                            <TextField floatingLabelText="policy num" onChange={ e => onChange("policyNum", e.target.value)} defaultValue={userInfo.policyNum}></TextField><br/>
                            <RaisedButton type="submit" className="create" label="create" primary={true} />
                        </form>
                    </div>
            }</div>
        );
    }
}

const mapStateToProps = (state) => {
  return {
    error: state.macReducer.error,
    userInfo: state.macReducer.userInfo,
    verifying: state.macReducer.verifying
  }
}

function verifyUserInfo(userInfo) {
    return dispatch => {
        dispatch({ type: 'verifying', payload: true});
        fetch('http://localhost:8080/backend/verify', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(userInfo)
        })
        .then(response => response.text())
        .then(isVerifySuccess => {
            if ("true" === isVerifySuccess) {
                dispatch({ type: 'verifying', payload: false});
                dispatch(push('/lossDetail'));
            } else {
                dispatch({ type: 'verify-fail'});
            }
        })
        .catch(error => {
            console.log("request failed: ", error);
            push('/error');
        })
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onChange: (field, value) => {
            dispatch({
                type: 'typing',
                payload: {field, value}
            })
        },
        onSubmit: (userInfo) => {
            dispatch(verifyUserInfo(userInfo))
        }
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Mac);

